package com.yc.starter.login.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc.starter.login.LoginProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    LoginProperties properties;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        System.out.println("handler = " + handler);
        HttpSession session = request.getSession();
        Object user = session.getAttribute(properties.getSessionKey());
        if (user == null) {
            // 未登录
            if (request.getHeader("Accept").contains("json")) {
                Map res = Map.of("code", 0, "msg", "未登录");
                response.setContentType("application/json;charset=UTF-8");
                new ObjectMapper().writeValue(response.getOutputStream(), res);
            } else {
                request.setAttribute("msg", "未登录");
                request.getRequestDispatcher("/error.html").forward(request, response);
            }
            return false;
        } else {
            // 已登录
            return true;
        }
    }
}
